<!--
tableData是原原数据
filterDataShow是原数据(展示在页面端的，刚开始是tableData的复制品，经过处理后会切割成不同的块分页展示)
form是临时暂存的数据 
-->
<template>
  <div class="hello">
    <el-container>
      <!-- 头部 -->
      <Header></Header>
    </el-container>
    <el-container>
      <el-container>
        <!-- 中间部分 -->
        <AsideLeft></AsideLeft>
        <el-main>
          <div>
            <div class="divel-table">
              <div style="width:90%;text-align: left;">
                <el-button
                  style="line-height: 100%;height:90%;align-items:center"
                  class="add_btn"
                  type="primary"
                  @click="addvaluestart()"
                  takeview
                  v-no-more-click
                >新增</el-button>
                <el-input
                  style="display:inline-block;width:40%;height:100%"
                  class="search-bar"
                  placeholder="输入关键字"
                  size="small"
                  v-model="keywords"
                  clearable
                ></el-input>

                <!--@selection-change="handleSelectionChange"
                //多选，当选择项发生变化时会触发该事件
                @row-click="handleRowClick"
                //点击每行时触发事件
                ref="handSelectTest_multipleTable"
                //添加属性
                row-key="id" -->

              </div>

              <!-- filterDataShow   tableData-->
              <el-table
                :data="filterDataShow.slice((currentPage-1)*pageSize,currentPage*pageSize)"
                height="250"
                max-height="350"
                border
                style="width: 90% "
                @selection-change="handleSelectionChange"
                @row-click="handleRowClick"
                ref="handSelectTest_multipleTable"
                row-key="id"
              >
                <!--:reserve-selection="true"选择其他页时，之前页选的的框依然存在 -->
                <el-table-column
                  type="selection"
                  label="点击全选"
                  align="center"
                  width="60"
                  :reserve-selection="true"
                >
                </el-table-column>
                <el-table-column
                  prop="name"
                  label="姓名"
                  align="center"
                  width="90"
                >
                </el-table-column>
                <!--<el-table-column
                  prop="age"
                  label="年龄"
                  align="center"
                  width="80"
                >
                </el-table-column> -->
                <el-table-column
                  prop="age"
                  label="年龄"
                  align="center"
                  width="80"
                  :formatter="TransitionAge"
                >
                  <!-- <template slot-scope="scope">
                    {{scope.row.age.TransitionAge}}
                  </template> -->
                </el-table-column>
                <el-table-column
                  prop="sex"
                  label="性别"
                  align="center"
                  width="80"
                >
                </el-table-column>
                <el-table-column
                  prop="telphone"
                  label="联系电话"
                  align="center"
                  width="130"
                >
                </el-table-column>
                <el-table-column
                  prop="'address.minor1,address.mainaddress'"
                  align="center"
                  label="详细地址"
                  min-width="300"
                  max-width="999"
                >
                  <template slot-scope="scope">

                    {{scope.row.address.mainaddress}} {{scope.row.address.minor1}}

                  </template>
                </el-table-column>

                <el-table-column
                  fixed="right"
                  align="center"
                  label="操作"
                  width="100"
                >
                  <!-- @click="takeview(scope.row)" -->
                  <!-- handleClick(scope.row),isShow=false -->
                  <!-- v-no-more-click  加入实现防抖 -->
                  <template slot-scope="scope">
                    <el-button
                      @click="takeview(scope.row,0)"
                      type="text"
                      size="small"
                      v-no-more-click
                      @click.stop="handleRowClick()"
                    >查看</el-button>
                    <el-button
                      type="text"
                      size="small"
                      v-no-more-click
                      @click="takeview(scope.row,1)"
                      @click.stop="handleRowClick()"
                    >编辑</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="addArea">
              <el-button
                type="danger"
                icon="el-icon-delete"
                @click="delAll"
                :disabled="multipleSelection.length === 0"
                style="margin-left:15pxborder-radius:25px;"
              >
                删除
              </el-button>

            </div>
            <!-- 分页器 -->
            <!-- <Pager></Pager> -->
            <div style="margin-top:15px;">
              <el-pagination
                style="text-align:center"
                margin-top=20px
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-size="pageSize"
                layout=" prev, pager, next, total,sizes,jumper"
                :total="filterDataShow.length"
                @size-change="handleSizeChange"
                :page-sizes="[2,5,10,20]"
              >
              </el-pagination>
            </div>

          </div>
        </el-main>
        <AsideRight></AsideRight>
      </el-container>

      <!-- 底部 -->
      <Footer></Footer>
    </el-container>

    <!-- 下面是弹出框 -->
    <!-- element ui 中自带的表单必填项校验输入空格时，依然能逃过验证（required: true还是可以通过），需要再 在v-model 加上 .trim 来禁止输入空格字符-->
    <el-dialog
      title="新建/编辑用户"
      :visible.sync="dialogVisible"
      width="70%"
      flex:1
      :before-close="handleClose"
    >
      <el-form
        ref="form"
        :model="form"
        label-width="auto"
      >
        <el-row>
          <el-col :span=12>
            <el-form-item
              label="姓名"
              prop="name"
            >
              <!-- isShow是表示可否编辑 -->
              <el-input
                v-model.trim="form.name"
                :disabled="!this.isShow"
                placeholder="请输入您的姓名"
                maxlength="10"
                show-word-limit
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span=12>
            <el-form-item
              label="性别"
              prop="sex"
            >
              <el-select
                v-model.trim="form.sex"
                placeholder="请选择性别"
                :disabled="!this.isShow"
                label-width="auto"
              >
                <el-option
                  label="男"
                  value="男"
                ></el-option>
                <el-option
                  label="女"
                  value="女"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span=12>
            <el-form-item
              label="联系电话"
              props="phone"
              label-width="auto"
            >
              <el-input
                v-model.trim="form.phone"
                onkeyup="value=value.replace(/[^\d]/g,'')"
                placeholder="请输入您的手机号码"
                :disabled="!this.isShow"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span=12>
            <!-- 33333 -->
            <el-form-item
              label="出生日期"
              props="age"
              label-width="auto"
            >
              <!-- Tue Feb 01 2022 00:00:00 GMT+0800 (中国标准时间)  默认返回格式   -->
              <!-- 改用时间戳，通用性更好  value-format="timestamp" -->
              <!-- :readonly="!this.isShow"   优化的时候可以用-->
              <el-date-picker
                :editable="false"
                v-model.trim="form.age"
                type="month"
                placeholder="选择年月"
                :disabled="!this.isShow"
                align="left"
                clearable:true
                :picker-options="timeChange"
                value-format="timestamp"
                format="yyyy 年 MM 月"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 区域码 -->
        <!-- 这里考虑到了在查看过程中，由于客户是没有任何点击操作的，所以要考虑到数据显示的完整性，故采用“地址”和“详细地址”都另开一行管理 -->
        <el-row>
          <el-col :span=17>
            <!-- <el-col :span=8> -->
            <el-form-item
              label="地址地区"
              prop="address"
              label-width="auto"
            >
              <!-- el-cascader-panel 待选样式 -->
              <!-- 这里设置style的时候 设置的大的原因是有可能出现“新疆维吾尔自治区 克孜勒苏柯尔克孜自治州 乌恰县 ”这样的地名 为了能够这样显示故将style的宽度变大-->
              <el-cascader
                style="width:34.7rem"
                debounce:300
                size="large"
                filterable
                :options="options"
                @change="handleChange"
                :disabled="!this.isShow"
                v-model.trim="form.address.maincode"
              >
              </el-cascader>

            </el-form-item>
            <!-- </el-col> -->
            <!-- <el-col :span=16> -->
            <el-form-item
              label="详细地址"
              placeholder="请输入详细地址"
              prop="address"
              label-width="auto"
              maxlength="300"
            >
              <el-input
                style="width:34.7rem "
                v-model.trim="form.address.minor1"
                :disabled="!this.isShow"
              ></el-input>
            </el-form-item>
            <!-- </el-col> -->
          </el-col>
        </el-row>
      </el-form>

      <span
        slot="footer"
        class="dialog-footer"
      >
        <!--   防抖 -->
        <!-- v-if="this.mode!==1" ==》当查看状态的时候 取消按钮不显示 -->
        <el-button
          @click="cancelDialog(),isShow=false,dialogVisible = false"
          v-no-more-click
          v-if="this.mode!==1"
        >取 消</el-button>
        <!-- dialogVisible = false,isShow=false  确定按钮 -->
        <el-button
          type="primary"
          @click="commitData(),dialogVisible = false,isShow=false"
          v-no-more-click
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
//引入头部文件
//import Header from "@/components/Header.vue";
import Header from "../components/UserManagement/Header.vue"; //头部
import Footer from "../components/UserManagement/Footer.vue"; //底部
import AsideLeft from "../components/UserManagement/Main/AsideLeft.vue"; //Main的右边部展示框
import AsideRight from "../components/UserManagement/Main/AsideRight.vue"; //Main的右部展示框
//import Pager from "../components/UserManagement/Main/Pager.vue"; //Pager.vue
import { regionDataPlus, CodeToText } from "element-china-area-data"; //引入区域码
import store from "../store/index";
import { mapMutations, mapActions, mapGetters, mapState } from "vuex"; //Vuex
export default {
  name: "HelloWorld",
  data() {
    return {
      form: {
        id: "",
        name: "",
        sex: "",
        age: "",
        phone: "",
        address: {
          mainaddress: "", //通过mainaddress获得  区域地址码
          //maincode: ["440000", "440100", "440113"],
          maincode: [],
          minor1: "", //详细地址
        },
        selectedOptions: [],
        delivery: false,
        type: [],
        resource: "",
        desc: "",
      },
      multipleSelection: [], //存放复选框选中的数组
      mode: 0,
      //模式说明mode==>初始：0 ，浏览：1 ，更改：2，新增：3，删除：4
      /* 做的时候疑问：通过单一mode返回值做判断，决定数据的下一步操作（查看数据、更新数据、新增数据、删除数据）这是否安全？别人能不能从控制台去修改值？前端能做安全措施怎么做 */
      options: regionDataPlus, //区域码
      checked: true,
      keywords: "", // 搜索的关键字
      filterDataShow: [], //储存符合条件的数据
      zdydialog: false, //显示
      dialogVisible: false, //dialog的隐藏maincode
      //dialogVisible: true,
      isShow: false, //控制是否显示输入框可编辑或显示提交按钮  默认不显示
      show: false, //是否是查看状态（查看数据标识符）
      update: false, //状态是否更新（更新数据标识符）
      add: false, //状态是否为新增（新增数据标识符）
      timeChange: {
        //时间选择框不能够选未来的时间
        disabledDate(time) {
          return time.getTime() >= Date.now() - 8.64e7; //如果没有后面的-8.64e7就是不可以选择今天的
        },
      },
      tableData: [
        {
          id: "1",
          name: "小明",
          sex: "男",
          age: "1643644800000",
          telphone: "13599999999",
          address: {
            mainaddress: "广东省 广州市 番禺区 ",
            maincode: ["440000", "440100", "440113"],
            minor1: "KFC1号  ",
          },
        },
        {
          id: "2",
          name: "小红",
          age: "1662393600",
          sex: "男",
          telphone: "13599999988",
          address: {
            mainaddress: "山东省 青岛市 市北区  ",
            maincode: ["370000", "370200", "370203"],
            minor1: "麦当劳2号 ",
          },
        },
        {
          id: "3",
          name: "小白",
          age: "1659715200",
          sex: "男",
          telphone: "1976550963",
          address: {
            mainaddress: "山东省 青岛市 崂山区  ",
            maincode: ["370000", "370200", "370212"],
            minor1: "华莱士3号 ",
          },
        },
        {
          id: "4",
          name: "小黑",
          age: "1484268957",
          sex: "男",
          telphone: "13599999966",
          address: {
            mainaddress: "辽宁省 沈阳市 市辖区  ",
            maincode: ["210000", "210100", "210101"],
            minor1: "老乡鸡4号 ",
          },
        },
        {
          id: "5",
          name: "小东",
          age: "1610092619",
          sex: "男",
          telphone: "13599999955",
          address: {
            mainaddress: "北京市 市辖区 朝阳区 ",
            maincode: ["110000", "110100", "110105"],
            minor1: "乡村鸡5号 ",
          },
        },
        {
          id: "6",
          name: "小南",
          age: "2588627428",
          sex: "男",
          telphone: "13599999944",
          address: {
            mainaddress: "广东省 广州市 荔湾区  ",
            maincode: ["440000", "440100", "440103"],
            minor1: "真功夫6号 ",
          },
        },
        {
          id: "7",
          name: "小西",
          age: "681142714",
          sex: "男",
          telphone: "13599999933",
          address: {
            mainaddress: "广东省 韶关市 武江区  ",
            maincode: ["440000", "440200", "440203"],
            minor1: "必胜客7号",
          },
        },
        {
          id: "8",
          name: "小北",
          age: "1146827857",
          sex: "男",
          telphone: "13599999922",
          address: {
            mainaddress: "广东省 广州市 白云区  ",
            maincode: ["440000", "440100", "440111"],
            minor1: "兰州拉面8号",
          },
        },
        {
          id: "9",
          name: "小芳",
          age: "2889109144",
          sex: "男",
          telphone: "13599999911",
          address: {
            mainaddress: "广东省 广州市 天河区  ",
            maincode: ["440000", "440100", "440106"],
            minor1: "沙县小吃9号 ",
          },
        },
        {
          id: "10",
          name: "小豪",
          age: "55892498",
          sex: "男",
          telphone: "13599999900",
          address: {
            mainaddress: "广东省 佛山市 顺德区  ",
            maincode: ["440000", "440600", "440606"],
            minor1: "驴肉火烧10号",
          },
        },
        {
          id: "11",
          name: "小宣",
          age: "1099796033",
          sex: "男",
          telphone: "13599999100",
          address: {
            mainaddress: "山东省 潍坊市 寒亭区 ",
            maincode: ["370000", "370700", "370703"],
            minor1: "肉夹馍11号",
          },
        },
      ],
      currentPage: 1, // 当前页码
      total: 20, // 总条数
      pageSize: 2, // 每页的数据条数
    };
  },
  components: {
    Header, //头部
    AsideLeft, //左边广告位置
    AsideRight, //右边广告位
    Footer, //底部栏目
    //Pager,
  },
  methods: {
    /* 删除框 开始 */
    //点击复选框触发，复选框样式的改变
    handleSelectionChange(val) {
      console.log(val); //打印选中的行集合
      this.multipleSelection = val;
    },
    //点击行触发，选中或不选中复选框
    handleRowClick(row, column, event) {
      this.$refs.handSelectTest_multipleTable.toggleRowSelection(row);
      console.log(row); //打印的时当前选中的行
    },
    //点击批量删除
    async delAll() {
      let arr = []; //let  存储点击被选中的对象
      //遍历点击选择的对象集合，拿到每一个对象的id添加到新的集合中
      this.multipleSelection.forEach((row) => arr.push(row.id));
      //this.multipleSelection = []; //事实上是将这个函数置为0了，那为什么arr里面还有值
      //this.$refs.multipleTable.clearSelection(); //清空里面的数据 报错 handSelectTest_multipleTable
      this.$refs.handSelectTest_multipleTable.clearSelection(); //终于搞定了！！！下次删除就不会叠加了
      console.log(arr, "arr");
      this.$confirm("确定删除吗", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success",
        callback: (action) => {
          if (action === "confirm") {
            //批量删除  执行批量删除方法
            //console.log(this.delAllIpserver(arr), "return"); //返回undifine 所以.then不起效//返回promise对象
            /* 报错：Uncaught TypeError: Cannot read properties of undefined (reading 'then')at callback  */
            this.delAllIpserver(arr) //Promise???
              .then((response, reject) => {
                this.$notify({
                  title: "删除成功",
                  message: (response, ""),
                  type: "success",
                  duration: 2000,
                });
                //this.getList();
                //重新加载页面的方法
              })
              .catch(() => {
                //console.log("response, reject error");
                //console.log("error submit");
              })
              .finally();
          }
          /* var p1 = new Promise(() => {}); */ //不行
        },
      });
    },

    async delAllIpserver(arr) {
      //实现回退的功能可以考虑建一个栈
      //arr 是 存放要被删除数据的id  遍历数组
      /* 问题记录：undefined is not iterable (cannot read property Symbol(Symbol.iterator)) at  
      for (let item of this.arr)   this  指向  捕获到未定义内容错误*/
      for (let item of arr) {
        //let一个index来接收findIndex的结果，这里arrText为要查找的数组
        let index = this.tableData.findIndex((ele) => {
          return ele.id === item;
        });
        console.log("index", index);
        //当查找失败返回
        if (index === -1) {
          return console.log("删除失败");
        }
        //如果找到该元素，使用splice方法删除元素
        this.tableData.splice(index, 1);
        //console.log(this.tableData, "tableData处理完的数据");
      }
      //后期修改，删除filterDataShow数据
      for (let item of arr) {
        //let一个index来接收findIndex的结果，这里arrText为要查找的数组
        let index = this.filterDataShow.findIndex((ele) => {
          return ele.id === item;
        });
        console.log("index", index);
        //当查找失败返回
        if (index === -1) {
          return console.log("删除失败");
        }
        //如果找到该元素，使用splice方法删除元素
        this.filterDataShow.splice(index, 1);
        //console.log(this.tableData, "tableData处理完的数据");
      }
      /* 这里return可以返回push进去的栈 */
      //返回promise
      delete this.arr;
      let p1 = new Promise((response, reject) => {
        if (1) {
          response(1);
        } else {
          reject(1);
        }
      });
      return p1;
    },
    /* 删除框 结束 */
    toChange() {
      this.checked = !this.checked; //选择反转
    },
    searchResource() {
      this.currentPage = 1; //将当前页设置为1，确保每次都是从第一页开始搜
      let filterKeywords = this.keywords.trim();
      //console.log("this is ", filterKeywords);
      let filerReasource = this.tableData.filter((item) => {
        //过滤全部数据
        //console.log("item", item);
        if (item.name.includes(filterKeywords)) {
          return item;
        }
      });
      this.filterDataShow = filerReasource; //将符合条件的内容赋给filterDataShow  filterDataShow是展示在页面端的数据
    },
    //转换实际时间数据来显示实际年龄  后端存时间戳性能更好
    TransitionAge(row) {
      //console.log(row.age);
      //当前时间 毫秒
      let nowTime = new Date().getTime();
      //一年毫秒数(365 * 86400000 = 31536000000)
      let age = (nowTime - row.age) / 31536000000;
      if (age > 1) {
        let re = parseInt(Math.round(age.toFixed(3)));
        return re; //四舍五入 然后向上取整整数/* 这里后期需要优化一下，涉及到许多类型的转换 num和string*/
      } else {
        let re = Number(age.toFixed(3)).toFixed(1);
        return re;
      }
    },
    async cancelDialog() {
      this.dialogVisible = false;
      /* 隐藏对话框并清空里面的记录 */
      this.form.id = "";
      this.form.name = "";
      this.form.sex = "";
      this.form.age = "";
      this.form.phone = "";
      this.form.address.mainaddress = "";
      this.form.address.maincode = ["440000", "440100", "440113"];
      //this.form.address.maincode = ["440000", "440100", "440113"]; //待会验证
      /*this.form.address.maincode[0] = "440000";
      this.form.address.maincode[1] = "440100";
      this.form.address.maincode[2] = "440113"; */
      this.form.address.minor1 = "";
      //this.mode = 0; //状态返回为初始状态
      this.modeChange(0); //状态返回为初始状态  置0
      return; //有return，then才起效
    },
    onSubmit() {},
    async handleClick(row) {
      console.log(row);
      //let newData = JSON.parse(JSON.stringify(row));
      //console.log(newData); || "出错了,请刷新"
      /*console.log("row.name", row.name);
      console.log("row.sex", row.sex);
      console.log("row.age", row.age);
      console.log("row.telphone", row.phone);
      console.log("row.address.mainaddress", row.address.mainaddress);
      console.log("row.address.maincode[0]", row.address.maincode[0]);
      console.log("row.address.maincode[1]", row.address.maincode[1]);
      console.log("row.address.maincode[2]", row.address.maincode[2]);
      console.log("row.address.minor1", row.address.minor1); */
      this.form.id = row.id.toString() || "加载出错了,请刷新";
      this.form.name = row.name.toString() || "加载出错了,请刷新";
      this.form.sex = row.sex.toString() || "加载出错了,请刷新";
      this.form.age = row.age || "加载出错了,请刷新";
      this.form.phone =
        row.telphone.toString() ||
        "加载出错了,请刷新"; /* 记录telphone写为phone了 */
      this.form.address.mainaddress =
        row.address.mainaddress.toString() || "加载出错了,请刷新";
      /*       this.form.address.maincode[0] = row.address.maincode[0];
      this.form.address.maincode[1] = row.address.maincode[1];
      this.form.address.maincode[2] = row.address.maincode[2]; */
      //没有错  获得的值和赋给form的值也是一样的，怀疑地址选择栏无法刷新
      /* let newData = JSON.parse(JSON.stringify(this.data)); */
      /* maincode: ["370000", "370200", "370202"], */
      this.form.address.maincode = [
        row.address.maincode[0].toString() || "加载出错了,请刷新",
        row.address.maincode[1].toString() || "加载出错了,请刷新",
        row.address.maincode[2].toString() || "加载出错了,请刷新",
      ];
      this.form.address.minor1 = row.address.minor1 || "加载出错了,请刷新";
      this.dialogVisible = true;
      console.log(this.form);
      return {
        row,
      };
    }, //打印本行的信息
    //每页条数改变时触发 选择一页显示多少行
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.currentPage = 1;
      this.pageSize = val;
    },
    //当前页改变时触发 跳转其他页
    handleCurrentChange(val) {
      //console.log(`当前页: ${val}`);
      this.currentPage = val;
    },
    //上部的关闭小按钮
    handleClose(done) {
      if (this.isShow) {
        this.$confirm("确认关闭？")
          .then((_) => {
            this.cancelDialog().then((_) => {
              //关闭时候清空暂存的数据 防止数据还没来得及更新就关闭 解决数据数据切换闪动
              done();
            });
          })
          .catch((_) => {});
      } else {
        this.cancelDialog().then((_) => {
          //关闭时候清空暂存的数据 防止数据还没来得及更新就关闭 解决数据数据切换闪动
          //this.modeChange(0); //将状态置0（初始状态）=>这里不用了this.cancelDialog()已经有了相同的功能了
          done();
        });
      }
      /*      return {
        //方法1，闭包返回对象  返回值对象实质上是一个 我们模块的公有API  闭包方法尝试不行，原因是function(e)！e待解决
        done: done,
      }; */
    },
    //打印区域码 区域码文字地址转换
    handleChange(value) {
      //value就是this.form.address.maincode
      //我们选择地址后，selectedOptions 会保存对应的区域码，例如北京的区域码为'110000'
      //我们要取出区域码对应的汉字，就需要用CodeToText(区域码)进行输出
      //对@change有个判断
      let name = "";
      this.form.address.maincode.map(
        (item) => (name += CodeToText[item] + " ")
      );
      this.form.address.mainaddress = name;
      console.log(this.form.address.mainaddress);
      console.log(this.form.address.maincode);
    },

    //点击增加按钮的预处理操作
    addvaluestart() {
      //点击清之前的内容后，下一步显示对话框
      this.cancelDialog() //这里走不通，需要return一个对象（其他原因）
        .then((_) => ((this.dialogVisible = true), (this.isShow = true))) //这里不能用then的原因是cancelDialog()没有声明为异步函数 async！！！
        .catch((_) => {});
      //await this.cancelDialog(); //两种方法。要不就在addvaluestart函数中声明为异步函数  第二种方法还在研究
      //await this.dialogVisible = true;  //不行await只能接函数
      /*this.dialogVisible;
      this.isShow; */
      this.handleChange(); //终于搞定了，浪费了N多时间，最主要是要在初始化之前通过默认的地址代码去赋值
      this.modeChange(3); //新增模式
      //刷新底部页面数字
    },
    //方法  根据传入值返回isshow的值
    async setIsshow(value) {
      return (this.isShow = Boolean(value)); //强制转换更安全
    },
    //根据点击更改状态
    async modeChange(value) {
      //模式说明mode==>初始：0 ，浏览：1 ，更改：2，新增：3，删除：4
      if ((this.mode = !0)) {
        this.mode = 0;
      }
      this.mode = value;
    },
    //点击查看操作
    async takeview(value, state) {
      //await this.addvaluestart(); //初始化
      //state 0==》浏览  state 1==更改
      console.log(value, "11");
      await this.handleClick(value); //给各个框赋原来元素的值
      if (state == 0) {
        await this.setIsshow(false); //内容不可修改状态
        await this.modeChange(1); //更改模式为浏览状态
      } else if (state == 1) {
        await this.setIsshow(true); //内容可修改状态
        await this.modeChange(2); //更改模式为更改状态
      } else {
        //这里是防止state出错了，进行一个state的重置
        await this.modeChange(0); //出错了则置为初始状态
        await this.cancelDialog(); //清除输入框内内容  //目前没有好的方法了点击进去页面会闪一下
        //弹框提示出错！
        this.$message({
          message: "系统载入错误请重新点击载入",
          type: "warning",
        });
      }
    },
    //点击更改数据
    changeData() {
      //原理通过id查找tableData中数据再更改
      console.log(this.form);
      let formid = this.form.id;
      console.log(formid, "id");
      let elementIndex = this.tableData.findIndex((obj) => obj.id == formid); //查找到所在的index
      this.tableData[elementIndex].name = this.form.name;
      this.tableData[elementIndex].sex = this.form.sex;
      this.tableData[elementIndex].age = this.form.age;
      this.tableData[elementIndex].telphone = this.form.phone;
      this.tableData[elementIndex].address.mainaddress =
        this.form.address.mainaddress;
      this.tableData[elementIndex].address.maincode =
        this.form.address.maincode;
      this.tableData[elementIndex].address.minor1 = this.form.address.minor1;
      /* this.tableData[elementIndex].name = this.form.address.maincode[0];
      this.tableData[elementIndex].name = this.form.address.maincode[1];
      this.tableData[elementIndex].name = this.form.address.maincode[2]; */
      console.log("After update: ", this.tableData[elementIndex]);
    },
    //点击增加数据
    addData() {
      let id1 = this.tableData.length + 1;
      /* 
      以下操作可以引起界面刷新：push，pop ，unshift，shift，reverse，sort，splice
      以下操作不会引起界面刷新：slice，concat ，filter 
      */
      let check = true;
      if (this.form.name == "") {
        check = false;
        console.log("check失败,form.name不能为空", this.form.name);
      }
      if (this.form.age == "") {
        check = false;
        console.log("check失败,form.age不能为空", this.form.age);
      }
      if (this.form.age == "") {
        check = false;
        console.log("check失败,form.age不能为空", this.form.age);
      }
      if (this.form.sex == "") {
        check = false;
        console.log("check失败,form.sex不能为空", this.form.sex);
      }
      if (this.form.phone == "") {
        check = false;
        console.log("check失败,this.phone不能为空", this.form.phone);
      }
      if (this.form.address.mainaddress == "") {
        check = false;
        console.log(
          "check失败,form.address.mainaddress不能为空",
          this.form.address.mainaddress
        );
      }
      if (this.form.address.maincode == "") {
        check = false;
        console.log(
          "check失败,form.address.maincode不能为空",
          tthis.form.address.maincode
        );
      }
      if (this.form.address.minor1 == "") {
        check = false;
        console.log(
          "check失败,form.address.minor1不能为空",
          this.form.address.minor1
        );
      }
      if (check) {
        let addData = {
          id: id1,
          name: this.form.name,
          age: this.form.age,
          sex: this.form.sex,
          telphone: this.form.phone,
          address: {
            mainaddress: this.form.address.mainaddress,
            maincode: this.form.address.maincode,
            minor1: this.form.address.minor1,
          },
        };
        /*         {
          id: "8",
          name: "小明明",
          age: "20",
          sex: "男",
          telphone: "13599999999",
          address: {
            mainaddress: "开封菜KFC-1号 ",
            maincode: ["370000", "370200", "370202"],
            minor1: "河南省 开封市 龙亭区 ",
          },
        }, */

        //提交到“远端”//console.log(this.tableData, "this.tableData");
        this.tableData.push(addData); //这里不能加this，吃大亏了
        //更新本地数据//console.log(this.filterDataShow, "this.filterDataShow");
        this.filterDataShow.push(addData); //这里不能加this，吃大亏了！！！！！！！吃大亏
        //因为这个this多写了 报mainaddress错 百思不得其解  后期需要查为什么
      } else {
        //提交失败取消所有提交（原因要填的填不够）
        this.cancelDialog();
        this.isShow = false;
        this.dialogVisible = false;
        this.$message.error("提交失败,您还有选项没有填写完整");
      }
    },
    //点击提交确定提交数据
    commitData() {
      //console.log(this.mode);
      //mode==>初始：0 ，浏览：1 ，更改：2，新增：3，删除：4
      if (this.mode === 0) {
        console.log("内部错误已重置");
      } else if (this.mode === 1) {
        console.log("当前状态是浏览状态");
      } else if (this.mode === 2) {
        console.log("当前状态是更改状态");
        //更改数据  changeData
        this.changeData();
      } else if (this.mode === 3) {
        console.log("当前状态是新增状态");
        //新增数据
        this.addData();
      } else if (this.mode === 4) {
        console.log("当前状态是删除状态");
        //删除数据;
      }
      this.modeChange(0); //恢复初始状态
      return;
    },
  },
  created() {
    this.filterDataShow = JSON.parse(JSON.stringify(this.tableData)); //深拷贝两个数组
    //this.getData();
    //tableData是原原数据
    //filterDataShow是原数据(展示在页面端的，刚开始是tableData的复制品，经过处理后会切割成不同的块分页展示)
    //form是临时暂存的数据
    //console.log(this.filterDataShow);
    //console.log(this.tableData); console.log(vue);
  },
  mounted() {
    this.searchResource(); //在页面挂载后调用此方法，确保数据与页面发生了交互   提前挂载函数？
    window.Vue = this; //控制台打印东西用
  },
  watch: {
    //监听搜索框内容，当搜索框内容发生变化时调用searchResource方法   当输入input框内的keywords发送变化则调用相应的函数
    keywords: {
      handler() {
        this.searchResource();
      },
    },
  },
  computed: {
    //showTable计算属性通过slice方法计算表格当前应显示的数据
    showTable() {
      return this.filterDataShow.slice(
        (this.currentPage - 1) * this.pagesize,
        this.currentPage * this.pagesize
      );
    },
    //获取用户token
    //...mapMutations(["getUserData"]),
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
/* 头部代码 */
/* 中间部分 */
.divel-table {
  /* 弹性布局 */
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 20px 3% 0px 3%;
  width: 98%;
  height: 400px;
  overflow: scroll;
  flex-direction: column;
}
.addArea {
  display: flex;
  margin-left: 50px;
  height: 40px;
  width: 900px;
  /* border: red 1px solid; */
}
/* ::v-deep .el-input__inner {
  padding: 0px;
}
.el-dialog__footer ::v-deep {
  display: none !important;
} */ //这里有个问题，无法穿透
/* :deep(.el-dialog__footer) {
  display: none !important;
} */
/* .dialog-footer {
  display: none;
} */
</style>
